package com.jgy.poi.word;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.jgy.entity.Stu;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 姜光远
 * @date 2023/4/10 16:47
 */
public class PoiWord {
    /**
     * 模板路径
     */
    String templatePath = "E:/springcloud/space-pro/space-parent/study-model/src/main/resources/template/testpoi.docx";

    /**
     * 压缩zip路径
     */
    String templateZip = "E:/word/poi/export.zip";
    //生成的word路径
    String fileDir = "E:/word/";
    //生成的文件名字
    String fileName = "exportpoi1";
    @Test
    public void test() throws FileNotFoundException {
        List<String> filePath = new ArrayList<>();
        HashMap<String, Object> exampleData = new HashMap<>(16);
        exampleData.put("myname", "admin");
        exampleData.put("myage", "123456");
        //要循环的数据
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            list.add(new Stu("老QI" + i, "2" + i,i+1));
        }
        exampleData.put("list", list);

        // 这里是行循环实例
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("list", policy).build();

        //通过模板创建word文档
        ZipUtils.createWord(templatePath,fileDir,fileName,exampleData,config);
        String path = fileDir + fileName + ".docx";
        filePath.add(path);

        //将创建的word文档压缩成zip
        ZipUtils.createZip(templateZip, filePath);

        //下载zip
        //ZipUtils.downLoadFile(templateZip,response);
    }
    public static void main(String[] args) throws IOException {
        //要写入模板的数据
        Map<String, Object> exampleData = new HashMap<>();
        exampleData.put("myname", "admin");
        exampleData.put("myage", "123456");
        //要循环的数据
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            list.add(new Stu("老QI" + i, "2" + i,i+1));
        }

        exampleData.put("list", list);
        // 这里是行循环实例
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("list", policy).build();
        //导入模板
        FileInputStream inputStream = new FileInputStream("space-parent/study-model/src/main/resources/template/testpoi.docx");
        //放入数据
        XWPFTemplate template = XWPFTemplate.compile(inputStream, config)
                .render(exampleData);
        //文件输出流
        FileOutputStream out = new FileOutputStream("E:/word/outpoi.docx");
        template.write(out);
        out.flush();
        out.close();
        template.close();
    }
}
